package com.link.base.base.product.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.link.base.base.common.model.Attachment;
import com.link.base.base.product.model.PcdData;
import com.link.base.base.product.service.PcdDataService;
import com.link.base.base.project.model.Project;
import com.link.base.base.project.service.ProjectService;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.controller.BasicControllerException;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.cllog.LCLogger;
import com.link.core.modules.export.FileIndexGenarate;
import com.link.core.util.CoreYmlConstants;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * pcd对象
 *
 * @date 2023-08-15 09:04:14
 */
@Controller
@RequestMapping("/link/pcdData")
public class PcdDataController extends BasicController<PcdData> {

    private static final Logger logger = LogManager.getLogger(PcdDataController.class);
    @Resource
    private KeyGenerateService keyGenerateService;

    @Resource
    private PcdDataService pcdDataService;

    @Resource
    private ProjectService projectService;

    @Override
    public BasicService<PcdData> getBasicService() throws Exception {
        return pcdDataService;
    }


    @RequestMapping(value = "/importFile", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> importFile(Attachment entity, HttpSession session, HttpServletRequest request,
                                      HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {

            String headIdParam = request.getParameter("headId");
            if (StringUtils.isBlank(headIdParam)) {
                throw new BasicControllerException("头信息为空异常，请刷新重新操作！");
            }
            Long headId = Long.parseLong(headIdParam);
            if (Objects.isNull(headId)) {
                throw new BasicControllerException("头信息转化异常，请刷新重新操作！");
            }
            // 若row_id为空，则后端生成id，并赋值
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile myfile = multipartRequest.getFile("uploadAttachment"); // 读取原始数据
            if (Objects.isNull(myfile)) {
                throw new BasicControllerException("上传文件异常，请重新操作！");
            }
            // 处理并读取数据
            pcdDataService.uploadExcelAnalysis(myfile,headId);
            // Attachment newEntry = attachmentService.insert(myfile, entity);
            result.put("success", true);
            result.put("entity", entity);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }


    @RequestMapping({"/queryByExamplePage/exportData"})
    @ResponseBody
    public Map<String, Object> exportData(@JsonParam PcdData entity, @JsonParam QueryParams qps,
                                          HttpSession session,
                                          HttpServletRequest request,
                                          HttpServletResponse response) {
        logger.info("导出列表...");
        Map<String, Object> result = new HashMap(4);

        try {
            qps.preDealSecurity(request);
            CoreUser user = UserUtil.getUser();
            if (null != user) {
                user.setExportType(qps.getExportFileType());
            }
            PcdData temp = BasicModel.transformClass(entity, qps);
            Filter filterProjectId = qps.getFilter("projectId", "=");
            if (Objects.isNull(filterProjectId)) {
                throw new BasicControllerException("请先选择所属项目！");
            }
            String value = filterProjectId.getValue();
            if (StringUtils.isBlank(value)) {
                throw new BasicControllerException("请先选择所属项目！");
            }
            Long projectId = new Long(value);
            if (Objects.isNull(projectId)) {
                throw new BasicControllerException("请先选择所属项目！");
            }
            Project project = projectService.queryById(projectId);
            if (Objects.isNull(project)) {
                throw new BasicControllerException("所属项目不存在！");
            }
            String projectCode = project.getProjectCode();
            String acctName = project.getAcctName();

            InputStream resourceAsStream = PcdDataController.class.getResourceAsStream("/template/pcd/pcd_tmp_001.xlsx");
            // String templateFileName = PcdDataController.class.getResource("/").getPath() + "template/pcd/pcd_tmp_001.xlsx";

            String fileNameWriter = getFilePath(UUID.randomUUID().toString(), ".xlsx");
            String abstFilePath = CoreYmlConstants.getTemporaryIOFileDir() + fileNameWriter;
            File exportFile = new File(abstFilePath);
            exportFile.getParentFile().mkdirs();
            /*Boolean createNewFileFlag = exportFile.createNewFile();
            if (createNewFileFlag) {
                logger.info("ExportWriter wirteData(List<?> list): 文件创建成功");
            } else {
                logger.error("ExportWriter wirteData(List<?> list): 文件创建失败");
            }*/
            ExcelWriter excelWriter = EasyExcel.write(abstFilePath).withTemplate(resourceAsStream).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().build();

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("projectCode", projectCode);
            map.put("acctName", acctName);
            excelWriter.fill(map, writeSheet);

            while (!qps.getStopExport()) {
                this.beforQueryAllOrExample(temp, request);
                this.beforQueryExample(temp, request);
                List<PcdData> list = this.getBasicService().queryByExamplePage(temp);
                if (qps.getPage() == 1) {
                    qps.setTotal(temp.getTotal());
                }
                if (!CollectionUtils.isEmpty(list)) {
                    excelWriter.fill(list, writeSheet);
                    temp.setPage(temp.getPage() + 1);
                    temp.setTotalFlag(temp.getTotalFlag());
                } else {
                    qps.setStopExport(true);
                }
                if ("Y".equals(qps.getExportCurrentPage())) {
                    break;
                }
            }
            // 千万别忘记关闭流
            excelWriter.finish();

            result.put("success", true);
            result.put("url", CoreYmlConstants.getTemporaryIOUrlDir() + fileNameWriter);
            result.put("code", "200");
        } catch (BasicServiceException var11) {
            logger.error("BasicController捕获异常: ", var11);
            result.put("success", false);
            result.put("result", var11.getMessage());
            result.put("detailMessage", var11.getDetailMessage());
            result.put("code", var11.getCode());
        } catch (Exception var12) {
            logger.error("BasicController捕获异常: ", var12);
            result.put("success", false);
            result.put("result", var12.getMessage());
            result.put("code", "400");
        }

        return result;
    }


    public String getFilePath(String fileName, String fileType) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat datetimeFormatter = new SimpleDateFormat("yyyyMMddHHmmsss");
        String relatePath;
        if (null != fileName && !"".equals(fileName)) {
            relatePath = "/export/" + dateFormatter.format(new Date()) + "/" + System.currentTimeMillis() + "/" + fileName + fileType;
        } else {
            relatePath = "/export/" + dateFormatter.format(new Date()) + "/" + fileName + datetimeFormatter.format(new Date()) + "_"
                    + FileIndexGenarate.getFileIndex(new Date()) + fileType;
        }
        logger.debug("导出文件路径为：" + relatePath);
        return relatePath;
    }

}
